package cn.com.backstage.controller;

import java.io.File;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import cn.com.api.entity.ApiJuan;
import cn.com.api.entity.ApiShop;
import cn.com.api.entity.ApiT_city;
import cn.com.api.entity.ApiT_products;
import cn.com.api.entity.ApiT_user_admin;
import cn.com.api.entity.ApiType;
import cn.com.api.service.ApiGoodsService;
import cn.com.api.service.ApiJuanService;
import cn.com.api.service.ApiShopsService;
import cn.com.api.service.ApiT_productsService;
import cn.com.api.service.ApiTypeService;
import cn.com.api.service.StartOnLoadService;
import cn.com.util.*;
import cn.com.util.*;
import cn.com.util.*;
import cn.com.util.*;

@Controller
@RequestMapping(Utils.SYS_BACKSTAGE)
public class JuanController {

	private static Logger logger = Logger.getLogger(JuanController.class);

	@Autowired
	private ApiGoodsService goodService;
	@Autowired
	private ApiTypeService apiTypeService;
	@Autowired
	private ApiT_productsService apiT_productsService;
	@Autowired
	private ApiShopsService apiShopsService;
	@Autowired
	private ApiJuanService apiJuanService;
	@Autowired
	private StartOnLoadService startOnLoadService;

	/**
	 * 进入查询界面
	 * 
	 * @return
	 */
	@RequestMapping(value = "juan-list")
	public ModelAndView juan_list(HttpServletRequest request, HttpServletResponse response, PageInfo page)
			throws Exception {
		ModelAndView mv = new ModelAndView("forward:/backstage/juan_list.jsp");
		List<Map<String, String>> map = new ArrayList<Map<String, String>>();
		Map<String, Object> cond = new HashMap<String, Object>();
		cond.put("types", new String[] { "0", "2", "3", "4" });
		map = apiJuanService.selectByModListPage(cond, page);
		mv.addObject("juan_list", map);
		mv.addObject("pageInfo", page);
		return mv;
	}

	/**
	 * 全城优惠劵列表
	 * 
	 * @return
	 */
	@RequestMapping(value = "juan_quan-list")
	public ModelAndView juan_quan_list(HttpServletRequest request, HttpServletResponse response, PageInfo page)
			throws Exception {
		ModelAndView mv = new ModelAndView("forward:/backstage/juan_quan_list.jsp");

		List<Map<String, String>> map = new ArrayList<Map<String, String>>();
		Map<String, Object> cond = new HashMap<String, Object>();
		cond.put("types", new String[] { "0", "2" });
		map = apiJuanService.selectByModListPage(cond, page);
		mv.addObject("juan_list", map);
		mv.addObject("pageInfo", page);
		return mv;
	}

	/**
	 * 进入新增全城优惠
	 * 
	 * @return
	 */
	@RequestMapping(value = "juan-quan-add-pre")
	public ModelAndView juan_quan_add_pre(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("forward:/backstage/juan_quan_add.jsp");

		//
		if (request.getParameter("id") != null) {
			String id = request.getParameter("id");
			Map<String, Object> juan = apiJuanService.selectById(id);
			mv.addObject("juan", juan);
		}

		List<ApiT_city> citys = startOnLoadService.citys();
		mv.addObject("citys", citys);

		List<Map<String, Object>> types = apiTypeService.getGoodsType(0);
		mv.addObject("types", types);

		List<ApiShop> shops = apiShopsService.searchShopsByEnable(1);
		mv.addObject("shops", shops);

		return mv;
	}

	/**
	 * 更新状态
	 * 
	 * @return
	 */
	@RequestMapping(value = "juan-quan-editstatus")
	public void juan_quan_editstatus(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();

		String c_enable = request.getParameter("enable");
		String id = request.getParameter("id");
		//
		if (id != null) {
			Map<String, Object> juan_obj = apiJuanService.selectById(id);

			JSONObject obj = JSONObject.fromObject(juan_obj);
			ApiJuan cur_juan = (ApiJuan) obj.toBean(obj, ApiJuan.class);
			cur_juan.setC_enable(Integer.valueOf(c_enable));

			boolean ret_result = apiJuanService.updateJuan(cur_juan);
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "更新状态成功！");
		}
		//
		PrintWriter out = response.getWriter();
		out.print(JsonUtil.object2json(map));
		out.close();

	}

	/**
	 * 进入新增页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "juan_quan-view")
	public ModelAndView juan_quan_view(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("forward:/backstage/juan_quan_view.jsp");

		//
		if (request.getParameter("id") != null) {
			String id = request.getParameter("id");
			Map<String, Object> juan = apiJuanService.selectById(id);
			mv.addObject("juan", juan);
		}

		List<ApiT_city> citys = startOnLoadService.citys();
		mv.addObject("citys", citys);

		List<Map<String, Object>> types = apiTypeService.getGoodsType(0);
		mv.addObject("types", types);

		List<ApiShop> shops = apiShopsService.searchShopsByEnable(1);
		mv.addObject("shops", shops);

		return mv;
	}

	/**
	 * 新增全城优惠券
	 * 
	 * @return
	 */
	@RequestMapping(value = "juan-quan-add")
	public void juan_quan_add(ApiJuan juan, HttpServletRequest request, HttpServletResponse response) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		String id = request.getParameter("id");
		// add
		if (id == null || (id.trim()).equals("")) {

			Date date = new Date();
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			juan.setC_appdate(format.format(date));
			ApiT_user_admin admin = (ApiT_user_admin) request.getSession().getAttribute("user_admin"); // 获取登录到系统的用户
			juan.setC_appuser(admin.getUser_name());
			juan.setUsed_count(0);
			juan.setReceive_count(0);
			//
			boolean ret_result = apiJuanService.insert(juan);
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "添加成功！");
		}
		// edit
		else {
			juan.setC_id(Integer.valueOf(id));
			//
			boolean ret_result = apiJuanService.updateJuan(juan);
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "编辑成功！");
		}
		//
		PrintWriter out = response.getWriter();
		out.print(JsonUtil.object2json(map));
		out.close();

	}

	/**
	 * 进入新增页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "juan-add-pre")
	public ModelAndView juan_add_pre(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("forward:/backstage/juan_add.jsp");
		Map<String, Object> juan = new HashMap<String, Object>();
		String area = "";
		if (request.getParameter("id") != null) {
			juan = apiJuanService.selectById(request.getParameter("id"));
			mv.addObject("juan", juan);
			area = juan.get("c_area") + "";
		}
		List<ApiT_city> citys = startOnLoadService.citys();
		mv.addObject("citys", citys);

		if (area.length() == 0) {
			// Map<String,Object> m=(Map<String,Object>)citys.get(0);
			// area=m.get("id")+"";
			area = citys.get(0).getId() + "";
		}

		List<ApiType> types = apiTypeService.getFirstTypes();
		mv.addObject("types", types);

		List<ApiShop> shops = apiShopsService.searchShopsByEnableAndCity("1", area);
		mv.addObject("shops", shops);

		return mv;
	}

	/**
	 * 新增优惠券
	 * 
	 * @return
	 */
	@RequestMapping(value = "juan-add")
	public void juan_add(ApiJuan juan, HttpServletRequest request, HttpServletResponse response) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		String id = request.getParameter("id");

		if (id == null || (id.trim()).equals("")) {

			Date date = new Date();
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			juan.setC_appdate(format.format(date));
			ApiT_user_admin admin = (ApiT_user_admin) request.getSession().getAttribute("user_admin"); // 获取登录到系统的用户
			juan.setC_appuser(admin.getUser_name());
			String cashed = request.getParameter("cashed");
			System.out.println("cashed=" + cashed);
			juan.setCashed(Float.valueOf(cashed));
			boolean ret_result = apiJuanService.insert(juan);
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "添加成功！");
		}
		// edit
		else {
			juan.setC_id(Integer.valueOf(id));
			juan.setCashed(Float.valueOf(request.getParameter("cashed")));
			System.out.println("cashed=" + juan.getCashed());
			boolean ret_result = apiJuanService.updateJuan(juan);
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "编辑成功！");
		}

	}

	/**
	 * 上传文件
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "juan-pics-upload")
	public void juan_pics_upload(@RequestParam(value = "file", required = false) MultipartFile file,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		String path = ImageUtils.getServletWebAppsPath(request) + "/juan/";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String sdfStr = sdf.format(new Date());
		String fileName = sdfStr + "_" + file.getOriginalFilename();

		File targetFile = new File(path, fileName);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		String logo_path = "";
		Map<String, Object> map = new HashMap<String, Object>();
		// 保存
		try {
			file.transferTo(targetFile);
			logo_path = ImageUtils.getDataBaseImagePath() + "/juan/" + fileName;

			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "上传成功！");
			map.put("datas", logo_path);

		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
		}
		//
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.print(JsonUtil.object2json(map));
		out.close();
	}

	/**
	 * 删除
	 * 
	 * @return
	 */
	@RequestMapping(value = "juan-delete")
	public void juan_delete(HttpServletRequest request, HttpServletResponse response) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		String id = request.getParameter("id");

		if (apiJuanService.delete(id)) {
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "删除成功！");
		}
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.print(JsonUtil.object2json(map));
		out.close();
	}

	@RequestMapping(value = "select_coupons")
	public ModelAndView select_coupons(HttpServletRequest request, HttpServletResponse response, PageInfo pageInfo)
			throws Exception {
		ModelAndView mv = new ModelAndView("forward:/backstage/select_coupons.jsp");
		// 查询选择优惠券
		String shop_id = request.getParameter("shop_id");
		String act_type = request.getParameter("act_type");
		String city_id = request.getParameter("city_id");
		String div_name = request.getParameter("div_name");
		String num = request.getParameter("num");
		System.out.println("div_name-" + div_name + "---num-" + num);
		Map<String, Object> conditions = new HashMap<String, Object>();
		conditions.put("shop_id", shop_id);
		conditions.put("act_type", act_type);
		conditions.put("city_id", city_id);
		List<Map<String, String>> map = new ArrayList<Map<String, String>>();
		map = apiJuanService.selectByModListPage(conditions, pageInfo);
		mv.addObject("coupons_list", map);
		mv.addObject("conditions", conditions);
		mv.addObject("city_id", city_id);
		mv.addObject("act_type", act_type);
		mv.addObject("div_name", div_name);
		mv.addObject("num", num);
		mv.addObject("pageInfo", pageInfo);
		return mv;
	}

}
